﻿using System.Collections.Generic;
using System.Threading.Tasks;
using SqlSugerexample.Model;
using SqlSugerexample.Models;
using SqlSugar;

namespace SqlSugerexample.Repositories
{
    public class UserRepository
    {
        public List<User> GetAll()
        {
            return DatabaseContext.Db.Queryable<User>().ToList();
        }

        public async Task<List<User>> GetAllAsync()
        {
            return await DatabaseContext.Db.Queryable<User>().ToListAsync();
        }

        public List<User> GetPagedUsers(int pageNumber, int pageSize)
        {
            return DatabaseContext.Db.Queryable<User>()
                .ToPageList(pageNumber, pageSize);
        }

        public List<User> GetSortedUsersByName(int pageNumber, int pageSize)
        {
            return DatabaseContext.Db.Queryable<User>()
                .OrderBy(u => u.Name)
                .ToPageList(pageNumber, pageSize);
        }

        public List<User> SearchUsersByName(string searchText)
        {
            return DatabaseContext.Db.Queryable<User>()
                .Where(u => u.Name.Contains(searchText))
                .ToList();
        }

        public void Insert(User user)
        {
            DatabaseContext.Db.Insertable(user).ExecuteCommand();
        }

        public void Update(User user)
        {
            DatabaseContext.Db.Updateable(user).ExecuteCommand();
        }

        public void Delete(User user)
        {
            DatabaseContext.Db.Deleteable(user).ExecuteCommand();
        }

        public void UpdateUserWithTransaction(User user)
        {
            DatabaseContext.Db.Ado.UseTran(() =>
            {
                DatabaseContext.Db.Updateable(user).ExecuteCommand();
                // 其他相关操作
            });
        }
    }
}
